import { useState, useEffect, useRef } from 'react';
import Modals from '@/components/modals/Modals';
import { PlusOutlined } from '@ant-design/icons';
import { FaqDataset } from '@/types/know/know';
import knowService from '@/api/services/knowService';
import { MAX_NAME_LENGTH, PaginationProps } from '@/common';
import NotData from '@/components/NotData';
import datasetService from '@/api/services/datasetService';
import { Input } from '@/components/eai-design';
import { message } from 'antd';

interface FaqListModalProps {
  open: boolean;
  onOk: (item: FaqDataset) => void;
  onCancel: () => void;
  appId: string;
}
export default function FaqListModal({ open, onOk, onCancel, appId }: FaqListModalProps) {
  const listRef = useRef<HTMLDivElement>(null);
  const [faqList, setFaqList] = useState<FaqDataset[]>([]);
  const [faqParams, setFaqParams] = useState<PaginationProps>({
    page: 1,
    page_size: 10,
    app_id: appId,
  });
  const [loading, setLoading] = useState(false);
  const [hasMore, setHasMore] = useState(true);
  const [addDatasetShow, setAddDatasetShow] = useState(false);
  const [inputValue, setInputValue] = useState('');
  const [selectedId, setSelectedId] = useState<string | undefined>();
  useEffect(() => {
    if (!open) {
      setFaqList([]);
    }
    setFaqParams({
      page: 1,
      page_size: 10,
      app_id: appId,
    });
    setSelectedId('');
  }, [open, appId]);

  useEffect(() => {
    if (open) {
      getFaqList(!!faqParams.page && faqParams.page > 1);
    }
  }, [faqParams.page, open]);
  const getFaqList = async (isLoadMore = false) => {
    setLoading(true);
    try {
      const res = await knowService.getFaqDatasetList(faqParams);
      if (isLoadMore) {
        setFaqList((prev) => [...prev, ...res.list]);
      } else {
        setFaqList(res.list);
      }
      setHasMore(res.list.length === faqParams.page_size);
    } finally {
      setLoading(false);
    }
  };
  const handleLoadMore = () => {
    if (loading || !hasMore) return;
    setFaqParams((prev) => ({
      ...prev,
      page: (prev.page || 1) + 1,
    }));
  };

  // 监听滚动
  const handleScroll = () => {
    const el = listRef.current;
    if (!el || loading || !hasMore) return;
    if (el.scrollHeight - el.scrollTop - el.clientHeight < 20) {
      handleLoadMore();
    }
  };

  const onAdd = async () => {
    try {
      await datasetService.createFaqDataset(inputValue, appId);
      message.success('新增成功');
      setAddDatasetShow(false);
      setInputValue('');
      setFaqParams((prev) => ({
        ...prev,
        page: 1,
      }));
      getFaqList();
    } catch (error) {
      message.error(error as string);
    }
  };

  return (
    <div>
      <Modals
        open={open}
        onCancel={onCancel}
        title="选择存放位置"
        width={420}
        modelContentClassName="!my-3 !pr-0 !py-3"
        footer={
          <div className="flex justify-end gap-2 border-t border-t-line-2 p-3">
            <div
              className={`ml-4 flex h-[32px] w-[68px] cursor-pointer items-center justify-center rounded-md border 
                   !border-@brand-color !text-@brand-color
              `}
              onClick={onCancel}
            >
              取消
            </div>
            <div
              style={
                selectedId
                  ? { background: 'linear-gradient(90deg, #1B6DFA 0%, #00D0FE 181.25%)' }
                  : {}
              }
              className={`ml-4 flex h-[32px] w-[68px]  items-center justify-center rounded-md border text-white 
                   ${
                     selectedId
                       ? 'cursor-pointer !border-@brand-color !bg-@brand-color'
                       : '!border-@brand-disabled cursor-not-allowed !bg-@brand-color-disabled'
                   }
              `}
              onClick={() => {
                if (selectedId) {
                  onOk(faqList.find((item) => item.datasetId === selectedId) || ({} as FaqDataset));
                }
              }}
            >
              完成
            </div>
          </div>
        }
      >
        <div className="flex items-center justify-between font-semibold">
          <span className="text-base">FAQ知识库</span>
          {faqList.length != 0 && (
            <div className="flex h-6 w-6 items-center justify-center rounded-md border border-line-2">
              <PlusOutlined className=" cursor-pointer" onClick={() => setAddDatasetShow(true)} />
            </div>
          )}
        </div>
        <div className="mt-2">
          {faqList.length > 0 ? (
            <div
              ref={listRef}
              style={{ maxHeight: 260, overflowY: 'auto', marginBottom: 16 }}
              onScroll={handleScroll}
            >
              {faqList.map((item, index) => (
                <div
                  key={item.datasetId || index}
                  className={`my-2 cursor-pointer rounded-md bg-bg-3 py-2 pl-3 text-sm text-text-5 ${
                    selectedId === item.datasetId ? 'font-semibold !text-@brand-color' : ''
                  }`}
                  onClick={() => setSelectedId(item.datasetId)}
                >
                  {item.datasetName}
                </div>
              ))}
              {/* {loading && (
              <div style={{ textAlign: 'center', color: '#999', padding: 8 }}>加载中...</div>
            )} */}
              {/* {!loading && hasMore && (
              <div style={{ textAlign: 'center', color: '#1677ff', padding: 8 }}>上拉加载更多</div>
            )} */}
            </div>
          ) : (
            <div style={{ textAlign: 'center', padding: '40px 0 24px 0' }}>
              <NotData fontText="暂无FAQ知识库" />
              <div
                onClick={() => setAddDatasetShow(true)}
                className={`m-auto mt-2 flex h-[32px] w-[150px] cursor-pointer items-center justify-center rounded-md border border-@brand-color text-@brand-color`}
              >
                新增FAQ知识库
              </div>
            </div>
          )}
        </div>
      </Modals>

      <Modals
        open={addDatasetShow}
        onCancel={() => {
          setAddDatasetShow(false);
        }}
        title="添加FAQ知识库"
        width={480}
        onOk={onAdd}
      >
        <Input
          value={inputValue}
          onChange={(e) => setInputValue(e.target.value)}
          placeholder="请输入"
          className="!h-10 rounded-lg !text-base"
          maxLength={MAX_NAME_LENGTH}
        />
      </Modals>
    </div>
  );
}
